package top.cptr.so.aliyundomainserver.aliyunSDKUtils;

import com.aliyun.alidns20150109.Client;
import com.aliyun.teaopenapi.models.Config;
import lombok.extern.slf4j.Slf4j;
import top.cptr.so.aliyundomainserver.aliyunSDKUtils.exception.AccessKeyIsNullException;
import top.cptr.so.aliyundomainserver.aliyunSDKUtils.exception.CreateClientException;
import top.cptr.so.aliyundomainserver.aliyunSDKUtils.pojo.AccessKey;


@Slf4j
public class ClientBeanFactory {
    /**
     * accessKey用户配置文件
     */
    private AccessKeysConfig accessKeysConfig;

    public ClientBeanFactory(AccessKeysConfig accessKeysConfig) {
        this.accessKeysConfig = accessKeysConfig;
    }

    public ClientBeanFactory(){}


    /**
     * 通过token获取阿里云连接客户端
     * @param token 用户token
     * @return 连接对象
     */
    public Client createClient(String token) throws CreateClientException {
        AccessKey accessKey = findAccessKey(token);
        if (accessKey==null){
            throw new AccessKeyIsNullException("AccessKeyIsNull");
        }
        return createClient(accessKey.getAccessKeyId(), accessKey.getAccessKeySecret());
    }

    /**
     * 创建阿里云连接客户端
     * @param accessKeyId accessKeyId
     * @param accessKeySecret accessKeySecret
     * @return 连接对象
     */
    public Client createClient(String accessKeyId, String accessKeySecret) throws CreateClientException {
        Config config = new Config();
        config.setAccessKeyId(accessKeyId);
        config.setAccessKeySecret(accessKeySecret);
        Client client;
        try {
             client = new Client(config);
        } catch (Exception e) {
            throw new CreateClientException("CreateClientError");
        }
        return client;
    }

    /**
     * 通过token获取accessKey
     * @param token 用户标识
     * @return AccessKey对象
     */
    private AccessKey findAccessKey(String token){
        if (token==null || token.equals("")) return null;
        for (AccessKey accessKey : accessKeysConfig.getAccessKeys()) {
            if (accessKey.getToken().equals(token)) {
                return accessKey;
            }
        }
        return null;
    }

    public AccessKeysConfig getAccessKeysConfig() {
        return accessKeysConfig;
    }

    public void setAccessKeysConfig(AccessKeysConfig accessKeysConfig) {
        this.accessKeysConfig = accessKeysConfig;
    }
}
